<template>
  <div v-if="pageShow" class="businessPage-wrapper" :class="[perviewPageContent ? 'perviewPage-wrapper' : null]">
    <div :class="['businessTopbar', params ? 'businessWindowTopbar' : null]">
      <div class="businessTitle-wrapper" v-if="!params">
        <div class="businessTitle-left">
          <span :class="['icon', 'iconfont', `${pageContent.icon}`]"></span>
          <span class="businessTitle">{{ pageContent.text }}</span>
        </div>
        <!-- TODO  筛选区 -->
        <div class="businessTitle-right">
          <div class="flow-wrapper" v-if="flowButtonShow">
            <div v-for="(item, i) in flowButtonComponents" :class="[item.attr]" :key="i" @click="search(1, i)">
              <span>{{ flowButtonNumMap[item.attr] }}</span>
              <span>{{ item.defaultValue }}</span>
            </div>
          </div>
          <el-input class="businessSearchInput" placeholder="名称或编号搜索" v-show="false">
            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
          <el-tooltip class="item" effect="dark" content="关闭预览" placement="top">
            <span style="z-index: 99" v-if="perviewPageContent" class="icon iconfont iconbiaoqianlan-guanbi"
              @click.stop="close"></span>
          </el-tooltip>
        </div>
      </div>
      <div :class="[
        'businessSearches-wrapper',
        params ? 'window-searches-wrapper' : '',
      ]">
        <div class="businessSearches-left" v-if="conditionShow">
          <div :class="[item.show ? null : 'hidden', 'businessSearchCondition']"
            v-for="(item, i) in searchComponents.slice(0, conditionIndex)" :key="i" :style="'width:' + item.width + 'px'">
            <label>{{ item.label }}</label>
            <component v-model="searchesMap[item.code]" value-key="value" :clearable="Boolean(item.clearable)"
              :disabled="item.type === 'eventInput' ? true : false" :is="item.renderer" :placeholder="item.placeholder"
              :type="item.type" :value-format="item.format" class="businessConditionInput"
              @dblclick.native="dblclick(item)" @visible-change="visibleChange(item)"
              @change="handleComponentChange(item)">
              <el-option v-for="item in selectOption[item.code]" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
            </component>
          </div>
          <div class="businessSearchCondition moreConditionsLabel" @click="handleMoreConditions"
            v-if="moreConditionLabelShow">
            <label>更多条件</label>
          </div>
          <hr />
          <div class="moreConditions" v-if="moreConditionsShow">
            <div :class="[item.show ? null : 'hidden', 'businessSearchCondition']" v-for="(item, i) in searchComponents.slice(
              conditionIndex,
              searchComponents.length
            )" :key="i" :style="'width:' + item.width + 'px'">
              <label>{{ item.label }}</label>
              <component v-model="searchesMap[item.code]" :clearable="Boolean(item.clearable)"
                :disabled="item.type === 'eventInput' ? true : false" :is="item.renderer" :placeholder="item.placeholder"
                :type="item.type" :value-format="item.format" class="businessConditionInput"
                @dblclick.native="dblclick(item)" @visible-change="visibleChange(item)"
                @change="handleComponentChange(item)">
                <el-option v-for="item in selectOption[item.code]" :key="item.value" :label="item.label"
                  :value="item.value"></el-option>
              </component>
            </div>
          </div>
        </div>
        <div class="businessSearches-right">
          <span class="businessButtonConfirm" @click="search(1)">立即查询</span>
          <span class="businessButtonCancel" @click="clearConditions">清空条件</span>
        </div>
      </div>
      <img v-if="!params" src="@/assets/image/img_style.png" class="imgBefore" />
      <img v-if="!params" src="@/assets/image/img_style.png" class="imgAfter" />
      <img v-if="!params" src="@/assets/image/img_style_night.png" class="imgBefore" />
      <img v-if="!params" src="@/assets/image/img_style_night.png" class="imgAfter" />
    </div>
    <div v-if="pageContentShow" class="businessContent-wrapper" :style="'height:' + contentHeight + 'px'">
      <!-- 按钮区 -->
      <div class="businessButtons-wrapper" v-if="!params || params.edit">
        <span v-for="(item, i) in buttonComponents" :class="[item.attr, 'button']" :key="i" @click="buttonClick(item)">{{
          item.defaultValue }}</span>
      </div>
      <!-- 列表渲染数据 -->
      <el-table v-if="tableShow" stripe :height="tableHeight" :data="tableData" class="businessTable" ref="pageTable"
        @selection-change="handleSelectionChange" @cell-click="handleCellClick" @row-dblclick="cellDbClick">
        <!-- 勾选框列宽不要改 -->
        <el-table-column type="selection" width="48"></el-table-column>
        <!-- 表单渲染组件 -->
        <my-column v-for="(item, index) in col" :key="index" :col="item" :options="item.options"></my-column>
      </el-table>
      <!-- 底部分页 -->
      <el-pagination class="businessPagination" :current-page="pageIndex" :total="totalCount" :page-size="pageSize"
        :page-sizes="[originPageSize, 10, 15, 20, 50]" background layout="total, sizes, prev, pager, next, jumper"
        @current-change="handleCurrentChange" @size-change="handleSizeChange"></el-pagination>
    </div>
    <!-- 流程图 -->
    <flow-view v-if="flowViewShow" :wfInstId="wfInstId" @close="flowViewHide"></flow-view>
    <!-- 新增按钮部门选择 -->
    <div class="businessMask" v-if="deptMapShow">
      <div class="businessDialog middle">
        <div class="dialog-header" v-winmove>
          <span>部门选择</span>
        </div>
        <div class="dialog-body">
          <el-table ref="table" :data="deptMap" class="businessTable" @selection-change="handleDeptChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="name" label="部门名称"></el-table-column>
            <el-table-column prop="parentDept" label="父级部门"></el-table-column>
            <el-table-column prop="code" label="部门编码"></el-table-column>
          </el-table>
        </div>
        <div class="dialog-footer right">
          <span class="businessButtonCancel" @click="getDeptId">确定</span>
          <span class="businessButtonCancel" @click="deptMapShow = false">取消</span>
        </div>
      </div>
    </div>
    <!-- 输入框双击事件选人&选部门弹窗 -->
    <OrganizationTree v-if="treeShow" :dialogTitle="treeTitle" :type="treeType" :dialogShow="1" :checkBoxShow="2"
      :propsParam="treeParam" @getCheckedRoles="getTreeData" @treeCancel="treeHide" />
    <!-- 菜单树弹窗 -->
    <MenuTree v-if="menuTreeShow" :dialogShow="true" :param="treeParam" type="0" @confirm="getTreeData"
      @cancel="treeHide" />
    <!-- 资金科目树 -->
    <FundAccountTree v-if="fundAccountTreeShow" :dialogShow="true" @confirm="getTreeData" @cancel="treeHide" />
    <!-- 物资类别树 -->
    <DataTree v-if="dataTreeShow" :isMask="true" :type="treeType" :dialogTitle="treeTitle" :param="treeParam"
      :params="treeParams" :checkBox="treeCheckbox" @getCheckedType="getTreeData" @treeCancel="dataTreeShow = false" />
    <!-- 导入文件弹窗 -->
    <div class="businessMask" v-if="importFileDialog">
      <div class="businessDialog middle">
        <div class="dialog-header" v-winmove>
          <span>导入</span>
        </div>
        <div class="dialog-body">
          <div class="businessInput" style="width: 100%; margin-bottom: 8px">
            <label class="name">处理方式</label>
            <el-select v-model="form.handleWay">
              <el-option v-for="(item, index) in handleWayMap" :key="index" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div class="businessInput" style="width: 100%; margin-bottom: 8px">
            <label class="name">上传文件</label>
            <el-input type="text" v-model="form.file" readonly></el-input>
            <el-upload class="upload-demo" style="width: 30px; height: 32px" ref="upload" :action="serverAPI"
              :file-list="fileList" :on-change="handleChange" :auto-upload="false" :show-file-list="false">
              <span class="icon iconfont icongonggong_gengduo_16" slot="trigger"
                style="line-height: 32px; color: #939599"></span>
            </el-upload>
          </div>
          <div class="errorMessage-wrapper" v-if="errorMessageShow">
            <div class="errorMessage">{{ errorMessage }}</div>
            <a :href="errorMessageUrl">更多</a>
          </div>
        </div>
        <div class="dialog-footer right">
          <span class="businessButtonCancel" @click="importFile">确定</span>
          <span class="businessButtonCancel" @click="importFileDialog = false">取消</span>
        </div>
      </div>
    </div>
    <!-- 表单弹窗 -->
    <cell-view v-if="cellViewShow" :cellAdd="cellAdd" :funcId="funcId" :funcCode="funcCode" :funcName="funcName"
      :getWorkRepdeptId="getWorkRepdeptId" :tdeptId="tdeptId" :wpId="wpId" :tworkId="workId" :nodeId="nodeId"
      :initParam="initParam" :businessInfo="businessInfoParam" v-on:close="handleCellView" @refreshpage="refreshpage"
      @cellAddEnd="cellAddEnd" @addReportIn="addReportIn"></cell-view>
    <!-- 自定义页面弹窗 -->
    <template-window v-if="templateWindowShow" :params="templateWindowParams" ref="templateWindow"
      @confirm="getWindowData" @cancel="handelTemplateWindow"></template-window>
    <!-- 按钮关联窗体弹窗 模块 -->
    <div class="businessMask" v-if="buttonComShow">
      <div class="businessDialog large relatedPage">
        <div class="dialog-body">
          <component :is="ButtonCom" :relatedWinParams="relatedWinParams"></component>
        </div>
        <div class="dialog-footer right">
          <span class="businessButtonCancel">确定</span>
          <span class="businessButtonCancel" @click="buttonComShow = false">取消</span>
        </div>
      </div>
    </div>
    <!-- 按钮关联窗体弹窗 弹窗 -->
    <component v-if="buttonComWinShow" :is="ButtonCom" :relatedWinParams="relatedWinParams" @close="handleRelatedPage">
    </component>
    <!-- 自定义系统内部组件弹窗 -->
    <!-- :before-close="handleClose" -->
    <el-dialog v-dialogDrag title="值班工作台" :visible.sync="customComponent" width="70%">
      <span>
        <component :is="ButtonCom" :userParams="userParams" @getUserConfirmData="getUserConfirmData"></component>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="userComConfirm">确 定</el-button>
        <el-button @click="customComponent = false">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 自定义外部内部组件弹窗 -->
    <!-- :before-close="handleClose" -->
    <el-dialog v-dialogDrag title="值班工作台" :visible.sync="isShowExternalPage" width="80%">
      <span>
        <iframe :src="externalPageSrc" frameborder="0" height="100%" width="100%"></iframe>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="getExternalPageConnfirm">确 定</el-button>
        <el-button @click="isShowExternalPage = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  pageShow,
  pageRemove,
  editAut,
  pageExport,
  pageImport,
  getWorkRep,
  pageCustom,
} from "@/system/api/customPage";
import { getFillDept } from "@/system/api/organization/organization";
import { request } from "@/utils/request";
import MyColumn from "./myColumn";
import "@/system/pages/cellView";
import FlowView from "@/system/components/winFlowView";
import winmove from "@/directives/winmove";
import OrganizationTree from "@/system/components/organizationTree";
import MenuTree from "@/system/components/menuTree";
import FundAccountTree from "@/business/components/fundAccountTree";
import TemplateWindow from "@/system/pages/customPage/templateWindow";
import DataTree from "@/business/components/commonTree.vue";

//import {buttonAddDemo} from './generator/templatePage.js'
import { pageUI } from "@/system/api/templatePage.js";
import { userevent } from "@/system/config/userevent.js";

const sys = require("@/system/api/sys.js");

export default {
  name: "TemplatePage",
  data() {
    return {
      cellAdd: null,
      pageContentShow: false,
      contentHeight: "",
      changeFlag: false,
      refer: {},
      pageContent: {},
      tableShow: false,
      pageShow: false,
      routeId: this.$route.params.id, // 页面 ID
      menuId: this.$route.meta.funcId, // 菜单 ID
      icon: this.$route.meta.icon,
      pageURL: "",
      searchComponents: [],
      searchesMap: {},
      objSearchCondition: {},
      buttonComponents: [],
      flowButtonComponents: [], // 流程按钮
      flowButtonNumMap: {
        businessButtonFlow_unreported: 0,
        businessButtonFlow_flowing: 0,
        businessButtonFlow_completed: 0,
        businessButtonFlow_invalid: 0,
      },
      flowButtonShow: false,
      col: [],
      totalCount: 0,
      pageIndex: 1,
      pageSize: 10,
      originPageSize: null,
      // table
      tableData: [],
      checkedData: [],
      rowLength: "",
      tableHeight: "",
      // 表单
      cellViewShow: false,
      funcId: "", // 菜单 ID
      funcCode: "", // 菜单 code
      funcName: "",
      tdeptId: "", // 部门
      wpId: "", // 表单
      workId: "", // 表单主键
      nodeId: 1, // 0-浏览 1-新增&编辑
      deptMap: [],
      checkedDept: [],
      deptMapShow: false,
      initParam: {},
      businessInfoParam: {},
      // 流程
      flowViewShow: false,
      wfInstId: "", // 流程实例 ID
      templateWindowShow: false,
      templateWindowParams: {},
      // 输入框双击事件树弹窗
      treeShow: false,
      currentDbclickComponent: {},
      treeTitle: null,
      treeType: null,
      treeParam: {},
      treeParams: {},
      treeCheckbox: null,
      selectOption: {},
      conditionIndex: null,
      conditionShow: false,
      moreConditionsShow: false,
      moreConditionLabelShow: false,
      currentButtonDetail: null,
      // 导入文件
      importFileDialog: false,
      fileList: [],
      file: "",
      form: {
        handleWay: 1,
        file: "",
      },
      serverAPI: process.env.VUE_APP_BASE_API + "/page/import",
      handleWayMap: [
        {
          value: 1,
          label: "只添加",
        },
        {
          value: 2,
          label: "只修改",
        },
        {
          value: 3,
          label: "添加或修改",
        },
      ],
      errorMessageShow: false,
      errorMessage: "",
      errorMessageUrl: "",
      comParam: {},
      menuTreeShow: false,
      fundAccountTreeShow: false,
      dataTreeShow: false,
      relatedPageRoute: "",
      buttonComShow: false,
      buttonComWinShow: false,
      relatedWinParams: {},
      getWorkRepdeptId: 0,
      columnContent: "", //新增字段
      filterCondition: null, //筛选条件
      clickTimeOut: null,
      componentType: null,
      userEvents: null,
      formBtnType: null,
      rowData: {}, //当前点击单元格行的数据
      columnData: {}, //当前选择列的数据
      isTurnPage: false, //当前页面是否执行分页
      customComponent: false, //自定义组件弹窗
      dblParamOut: {}, //页面返回参数对象
      itemSqlBrAfter: "", //自定义脚本
      paramOut: {}, //弹出框选择数据返回对象
      userParams: {}, //用户自定义组件传参
      getUserComData: {}, //获取子组件返回值
      isShowExternalPage: false, //是否显示外部系统页面
      externalPageSrc: "", //外部系统页面地址
    };
  },
  components: {
    MyColumn,
    FlowView,
    OrganizationTree,
    TemplateWindow,
    MenuTree,
    FundAccountTree,
    DataTree,
  },
  directives: {
    winmove,
  },
  props: {
    perviewPageContent: null,
    params: {
      id: null, // 页面 id
      menuCode: null, // 页面编码
      multipleChoice: 0, // 0-单选 1-多选
      dialogTitle: null, // 标题
      deptId: null, // 部门 ID
      params: {}, // 传给后台的数据
      cellParams: {}, // 按钮传给表单参数
      businessInfo: {}, // 按钮传给表单后台参数
      serverParams: {}, // 按钮传给后台参数
    },
  },
  watch: {
    async $route(to) {
      this.routeId = to.params.id;
      this.icon = to.meta.icon;
      this.menuId = to.meta.funcId;
      this.cellViewShow = false;
      this.conditionShow = false;
      await this.pageInitialize();
      this.$nextTick(() => {
        this.getSearchesNum(); // 判断搜索框显示个数
      });
      setTimeout(() => {
        this.getContentHeight();
      }, 50);
      //执行方法
      this.setSYS();
    },
  },
  computed: {
    ButtonCom() {
      const self = this;
      console.log("relatedPageRoute::::" + self.relatedPageRoute);
      if (!self.relatedPageRoute) return "";
      return function (resolve) {
        switch (self.componentType) {
          case 1:
            require([
              "@/system/pages/customPage/" + self.relatedPageRoute,
            ], resolve); //界面组件
            break;
          case 2:
            require(["@/system/pages/" + self.relatedPageRoute], resolve); //表单
            break;
          case 4:
            require([
              "@/system/pages/userDefined/" + self.relatedPageRoute,
            ], resolve); //自定义组件
            break;
          default:
            require([
              "@/business/pages" + self.relatedPageRoute + ".vue",
            ], resolve);
            break;
        }
      };
    },
  },
  async mounted() {
    await this.pageInitialize();
    this.$nextTick(() => {
      this.getSearchesNum(); // 判断搜索框显示个数
    });
    setTimeout(() => {
      this.getContentHeight();
    }, 50);
    this.setSYS();
  },

  methods: {
    getExternalPageConnfirm() {
      //获取外部数据
      sys["VUE"] = this;
      sys.func(sys, this.itemSqlBrAfter);
      this.isShowExternalPage = false;
    },
    getUserConfirmData(e) {
      this.getUserComData = e;
    },
    userComConfirm() {
      /*
       *@functionName:
       *@params1: 参数1
       *@description: 用户自定义组件弹出框确定事件
       *@author: xuzhaoqian
       *@date: 2021-07-14 18:52:33
       *@version: V1.0.5
       */
      this.customComponent = false;
      console.log("ddddddddddddddd", this.getUserComData);
    },
    setSYS() {
      // 将界面对象对象放置到系统控制组件中   按钮区
      sys["baseURL"] = sessionStorage.getItem("baseURL");
      sys["VUE"] = this;
      this.buttonComponents.forEach((element) => {
        sys[element.code] = element;
      });
      // 统计区
      this.flowButtonComponents.forEach((element) => {
        sys[element.code] = element;
      });
      // 检索区
      if (this.searchComponents) {
        this.searchComponents
          .slice(0, this.conditionIndex)
          .forEach((element) => {
            sys[element.code] = element;
          });
      }
      // 表格对象
      sys["pageTable"] = this.$refs.pageTable;
      //表头数据
      sys["col"] = this.col;
      //加载初始化脚本
      sys.func(sys, this.pageContent.initJs);
    },
    cellAddEnd() {
      this.cellAdd = null;
    },
    handleCellClick(e, row, column, event, cell) {
      if (row.type == "selection") {
        return;
      }
      this.rowData = e;
      this.columnData = row;
      /**
       * 表格单击事件,设置延迟事件，在300毫秒内点击一次则认为是单击事件，单机两次则是双击事件
       * 筛选出当前信息
       */
      let activeRow = this.col.filter((item) => {
        return item.prop == row.property;
      });
      let activeRowType = activeRow[0].type;
      //执行JS脚本
      if (activeRow[0].hasOwnProperty("sql")) {
        sys.func(sys, activeRow[0].sql);
      }
      clearTimeout(this.clickTimeOut);
      this.clickTimeOut = setTimeout(() => {
        /**
         * 1、当前表头关联 界面、组件还是表单
         *
         */
        switch (activeRowType) {
          case 0:
            //系统组件
            console.log("系统组件。。。。");
            break;
          case 1:
            //自定义界面
            let dblParamIn = JSON.parse(activeRow[0].dblParamIn);
            this.templateWindowShow = true;
            this.templateWindowParams.id = dblParamIn.id;
            this.templateWindowParams.menuCode = dblParamIn.menuCode;
            this.templateWindowParams.multipleChoice =
              dblParamIn.multipleChoice;
            this.templateWindowParams.dialogTitle = activeRow[0].dblcomText;
            this.templateWindowParams.params = activeRow[0].params;
            break;
          case 2:
            //自定义表单
            this.formBtnType = "add";
            this.cellDbClick(JSON.parse(activeRow[0].dblParamIn));
            break;
          case 3:
            //自定义链接
            window.open(activeRow[0].dblcomText); //在新窗口打开链接
            break;
          case 4:
            //自定义组件
            this.templateWindowShow = true;
            break;
        }
      }, 300);
    },
    handleClose() {
      //dialog弹出框关闭事件
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => { });
    },
    getContentHeight() {
      if (this.params && this.params.id) {
        // 弹窗
        this.contentHeight =
          472 -
          document.getElementsByClassName("window-searches-wrapper")[0]
            .offsetHeight -
          12;
      } else {
        const pageHeight = document.getElementsByClassName(
          "businessPage-wrapper"
        )[0].offsetHeight;
        const topHeight =
          document.getElementsByClassName("businessTopbar")[0].offsetHeight;
        this.contentHeight = pageHeight - topHeight - 12;
      }
      this.pageContentShow = true;
      setTimeout(() => {
        this.getTableHeight();
      }, 50);
    },
    getTableHeight() {
      this.tableShow = false;
      this.tableHeight =
        this.params && !this.params.edit
          ? this.contentHeight - 56
          : this.contentHeight - 120;
      const tableBodyHeight = this.tableHeight - 40;
      this.pageSize = parseInt(tableBodyHeight / 40);
      this.originPageSize = this.pageSize;
      this.tableShow = true;
      this.search(1);
    },
    // 页面初始化
    async pageInitialize() {
      if (this.perviewPageContent) {
        // 预览
        this.pageContent = this.perviewPageContent;
      } else if (this.params && this.params.id) {
        // 弹窗
        await pageShow({
          id: this.params.id,
          menuCode: this.params.menuCode,
          edit: this.params.edit ? this.params.edit : false,
        }).then((res) => {
          if (res.success) {
            this.pageContent = res.info;
            console.log("弹窗", res.info);
          } else {
            this.message(res.msg, 3);
            return;
          }
        });
      } else {
        // 模块
        await pageShow({
          id: this.routeId,
          menuId: this.menuId,
          edit: true,
        }).then((res) => {
          if (res.success) {
            console.log("模块", JSON.stringify(res.info));
            //TODO 重新切换模块
            this.filterCondition = null;
            this.pageContent = res.info;
          } else {
            this.message(res.msg, 3);
            return;
          }
        });
      }
      // 页面模板类型（流程&非流程）
      if (this.pageContent.template === "1") {
        this.flowButtonShow = true;
      }
      // 下拉搜索框初始化
      this.searchComponentsInitialize();
      // 按钮初始化
      const children = this.pageContent.control.children;
      this.buttonComponents = [];
      if (children[1].children) {
        this.flowButtonComponents = [];
        children[1].children.forEach((item) => {
          if (item.type === "button") {
            this.buttonComponents.push(item);
          } else if (item.type === "flowButton") {
            this.flowButtonComponents.push(item);
          }
        });
      }
      // 表头初始化
      // console.log("children[2]::::    " + JSON.stringify(children[2].extattr));
      this.col = this.tableInitialize(children[2].extattr);
      // console.log("col::::   " + JSON.stringify(this.col));
      // 表格数据
      this.pageURL = this.pageContent.url;
      this.pageShow = true;
    },
    searchComponentsInitialize() {
      const children = this.pageContent.control.children;
      this.searchComponents = children[0].children;
      console.log(
        "this.searchComponents::" + JSON.stringify(this.searchComponents)
      );
      if (this.searchComponents) {
        let arr = {};
        this.searchComponents.forEach((Element) => {
          if (Element.refer) {
            this.refer[Element.refer] = Element;
          }
          let param = Element.code;
          arr[param] = Element.defaultValue;
          if (Element.dataType === 2) {
            // 自定义键值对
            this.selectOption[param] = JSON.parse(Element.data);
          } else if (Element.dataType === 1) {
            // 请求地址
            request({
              url: Element.url,
              method: "post",
            }).then((res) => {
              const element = JSON.parse(Element.data);
              let map = [];
              if (res.info) {
                res.info.forEach((item) => {
                  const obj = {
                    value: item[element.key],
                    label: item[element.value],
                  };
                  map.push(obj);
                });
              }
              this.selectOption[param] = map;
            });
          } else if (Element.dataType === 3 && !Element.refer) {
            // 下拉 sql 语句无参照列
            request({
              url: Element.url,
              method: "post",
            }).then((res) => {
              let map = [];
              let value = "";
              let label = "";
              const keyMap = JSON.parse(Element.data);
              keyMap.forEach((item) => {
                for (let key in item) {
                  if (key === "value") {
                    value = item[key];
                  } else if (key === "label") {
                    label = item[key];
                  }
                }
              });
              if (res.info) {
                res.info.forEach((item) => {
                  const obj = {
                    value: item[value],
                    label: item[label],
                  };
                  map.push(obj);
                });
              }

              this.selectOption[param] = map;
            });
          }
        });
        this.searchesMap = JSON.parse(JSON.stringify(arr));
        // 表单有传值
        if (this.params) {
          if (this.params.params && Object.keys(this.params.params).length) {
            for (let param in this.params.params) {
              if (!this.params.params[param]) {
                this.searchesMap[param] = "nullValue"; // 表单有传值且为空
              } else {
                this.searchesMap[param] = this.params.params[param];
              }
            }
          }
        }
      }
    },
    getSearchesNum() {
      const components = this.searchComponents;
      if (!components) {
        this.conditionShow = false;
        return;
      }
      const searchesLeftWidth = this.params
        ? 872 // 弹窗
        : document.getElementsByClassName("businessSearches-wrapper")[0]
          .offsetWidth - 32;
      let width = 0;
      for (let i = 0; i < components.length;) {
        if (components[i].show) {
          width = width + components[i].width + 12;
        }
        if (searchesLeftWidth - width < 94) {
          this.conditionIndex = i - 1;
          this.moreConditionLabelShow = true;
          this.conditionShow = true;
          return;
        } else {
          i++;
        }
        if (i === components.length) {
          this.moreConditionLabelShow = false;
          this.conditionShow = true;
          this.conditionIndex = components.length;
        }
      }
    },
    getFlowButtonNum(e, arr) {
      request({
        url: e.url,
        method: "post",
        data: {
          menuId: this.menuId,
          params: arr,
        },
      }).then((res) => {
        this.flowButtonNumMap[e.attr] = res.info;
      });
    },
    // 表格格式化
    tableInitialize(data) {
      const originTable = JSON.parse(data);
      let tableHeader = [];
      if (originTable.length !== 0) {
        let rowsMap = originTable.rows;
        delete rowsMap.len;
        this.rowLength = Object.keys(rowsMap).length;
        for (let i = 0; i < this.rowLength; i++) {
          let row = originTable.rows[i].cells;
          if (i < this.rowLength) {
            for (let key in row) {
              let data = {
                rowLine: i,
                label: row[key].text,
                minColumn: Number(key),
                maxColumn: row[key].merge
                  ? Number(key) + row[key].merge[1]
                  : Number(key),
                children: [],
                prop: row[key].prop,
                timeFormat: row[key].timeFormat,
                width: row[key].width,
                options: row[key].options ? JSON.parse(row[key].options) : null,
                //TODO 新增字段
                coloumTypeValue: row[key].coloumTypeValue,
                doubleEvent: row[key].doubleEvent,
                dblParamIn: row[key].dblParamIn,
                dblParamOut: row[key].dblParamOut,
                dblvue: row[key].dblvue,
                dblcomId: row[key].dblcomId,
                dblcomText: row[key].dblcomText,
                onlyOne: row[key].onlyOne,
                type: row[key].type,
                sql: row[key].sql,
                mouseEvenType: row[key].mouseEvenType,
              };
              if (i === 0) {
                tableHeader.push(data);
              } else {
                tableHeader.forEach((item) => {
                  if (
                    data.minColumn >= item.minColumn &&
                    data.maxColumn <= item.maxColumn
                  ) {
                    item = this.findParent(item, data);
                  }
                });
              }
            }
          }
        }
      }
      return tableHeader;
    },
    findParent(array, children) {
      if (array.rowLine - children.rowLine < -1) {
        if (array.children.length > 0) {
          for (let i = 0; i < array.children.length; i++) {
            this.findParent(array.children[i], children);
          }
        }
      } else if (array.rowLine - children.rowLine === -1) {
        if (
          children.minColumn >= array.minColumn &&
          children.maxColumn <= array.maxColumn
        ) {
          array.children.push(children);
          return array;
        }
      }
    },
    // 关闭预览
    close() {
      console.log("关闭预览.........");
      this.$emit("perviewPageClose", "close");
    },
    // 翻页
    handleCurrentChange(e) {
      this.pageIndex = e;
      this.search(this.pageIndex);
      this.isTurnPage = true;
    },
    // 每页显示页码
    handleSizeChange(e) {
      this.pageSize = e;
      this.search(this.pageIndex);
    },
    // 查询
    async search(pageIndex, filterIndex) {
      console.log("查询条件：" + JSON.stringify(pageIndex));
      console.log("筛选条件：" + JSON.stringify(filterIndex));
      if (filterIndex != undefined) {
        this.filterCondition = filterIndex; //筛选条件
      }
      this.pageIndex = pageIndex;
      console.log("filterIndex:::" + JSON.stringify(filterIndex));
      const arr = await this.getFormattingCondition(filterIndex);
      console.log("请求参数：" + JSON.stringify(arr));
      console.log("pageURL:::", this.pageURL);
      console.log("params:::" + JSON.stringify(this.params));
      if (this.pageURL) {
        request({
          url: this.pageURL,
          method: "post",
          params: {
            pageSize: this.pageSize,
            pageIndex: pageIndex - 1,
            menuId: this.params ? null : this.menuId,
            menuCode: this.params ? this.params.menuCode : null,
            params: arr,
          },
        }).then((res) => {
          if (res.success) {
            this.totalCount = res.totalCount;
            this.tableData = res.info;
            if (this.filterCondition == null) {
              //TODO 点击筛选后筛选区数字不变
              this.flowButtonComponents.forEach((item) => {
                this.getFlowButtonNum(item, arr);
              });
            }
            // this.checkedData
            //把渲染数据压入SYS
            sys["tableData"] = this.tableData;
          } else {
            this.message(res.msg, 3);
          }
        });
      }
    },
    getFormattingCondition(parameter) {
      console.log("searchesMap::::", JSON.stringify(this.searchesMap));
      let arr = [];
      //检索区事件处理
      for (let param in this.searchesMap) {
        if (this.searchesMap[param] || this.searchesMap[param] === 0) {
          this.searchComponents.forEach((item) => {
            let obj = {};
            if (item.code === param) {
              obj = {
                name: item.attr,
                value:
                  item.type === "eventInput"
                    ? item.defaultValue
                    : this.searchesMap[param],
                type: item.extattr,
                code: item.code,
              };
              if (this.objSearchCondition[item.code]) {
                // 键值对
                obj.value = this.objSearchCondition[item.code];
              }
              if (obj.value === "nullValue") {
                // 表单有传值且为空
                obj.value = "";
              }
              arr.push(obj);
            }
          });
        }
      }
      //TODO 判断当前是否选定筛选条件
      if (this.filterCondition != null) {
        let paramObj = {
          name: "WF_STATE ",
          value: 0,
          type: "string_like",
          code: "select_14",
        };
        if (this.filterCondition != 3) {
          paramObj.value = this.filterCondition;
        } else {
          paramObj.value = -1;
        }
        arr.push(paramObj);
      }
      return arr;
    },
    clearConditions() {
      //TODO 清空筛选区记录
      this.filterCondition = null;
      //清空条件是不清空隐藏条件
      if (this.searchComponents) {
        let arr = {};
        let obj = {};
        this.searchComponents.forEach((Element) => {
          if (Element.show) {
            let param = Element.code;
            arr[param] = Element.defaultValue;
          } else {
            return;
          }
        });
        obj = JSON.parse(JSON.stringify(arr));
        for (let key in obj) {
          this.searchesMap[key] = "";
        }
      }
      this.search(1);
    },
    // 表格勾选
    handleSelectionChange(e) {
      const data = JSON.parse(JSON.stringify(e));
      if (this.params && this.params.multipleChoice == 0 && e.length > 1) {
        // 单选
        this.$refs.pageTable.clearSelection();
        this.$refs.pageTable.toggleRowSelection(e.pop());
        this.checkedData = data.splice(1);
      } else {
        if (this.params && this.params.multipleChoice == 0) {
          this.checkedData = data;
        } else if (this.params && this.params.multipleChoice == 1) {
          if (this.isTurnPage) {
            this.checkedData = this.checkedData.concat(data);
          } else {
            this.checkedData = data;
          }
        } else {
          if (this.isTurnPage) {
            this.checkedData = this.checkedData.concat(data);
          } else {
            this.checkedData = data;
          }
        }
      }
      if (this.params) {
        this.$emit("getCheckedData", this.checkedData);
      }
    },
    // 表格双击浏览
    async cellDbClick(e) {
      clearTimeout(this.clickTimeOut);
      if (this.formBtnType == null) {
        this.workId = e[this.pageContent.primaryName];
        this.wpId = await this.getWpId(e);
        this.nodeId = 0;
      } else {
        this.wpId = await request({
          url: "/wp/getRepIdByClassId",
          method: "GET",
          params: {
            repClassId: e.repClassId,
          },
        })
          .then((result) => {
            return result.info;
          })
          .catch((error) => { });
        this.workId = e.workId;
        this.nodeId = e.nodeId;
      }
      this.$nextTick(() => {
        if (this.wpId !== 0) {
          this.cellViewShow = true;
          this.formBtnType = null;
        }
      });
    },
    async getWpId(e) {
      let wpId = null;
      if (e.REP_ID) {
        wpId = e.REP_ID;
      } else {
        await getWorkRep({
          workTable: this.pageContent.tableName,
          workKey: this.pageContent.primaryName,
          workId: e[this.pageContent.primaryName],
          funcId: this.$route.meta.funcId,
        }).then((res) => {
          if (res.success) {
            wpId = res.info.repId;
            this.getWorkRepdeptId = res.info.deptId;
          } else {
            this.message(res.msg, 3);
            return;
          }
        });
      }
      return wpId;
    },
    // 按钮点击
    buttonClick(item) {
      console.log(item.sql);
      console.log(this);
      let sql = "";
      if (item.sql.indexOf("<br>") != -1) {
        sql = item.sql.split("<br>")[0];
        this.itemSqlBrAfter = item.sql.split("<br>")[1];
      } else {
        sql = item.sql;
      }
      if (item.attr != "businessButtonAdd") {
        if (sys.haveAut(item)) {
          //有权限 itemSqlBrAfter
          sys["VUE"] = this;
          sys.func(sys, sql);
        } else {
          this.message("没有操作权限", 3);
        }
      } else {
        this.wpId = "";
        this.workId = "";
        sys.returnItem(item);
        sys.func(sys, sql);
      }

      return;
      //this[item.code] = item;
      // sysFunc(this,"alert(that.this.button_11.defaultValue)");
      this.funcId = "";
      this.funcCode = "";
      this.funcName = "";
      this.tdeptId = "";
      this.wpId = "";
      this.workId = "";
      this.nodeId = 1;
      this.currentButtonDetail = item;
      switch (item.attr) {
        case "businessButtonAdd": // 新增
          this.buttonAdd(item);
          break;
        case "businessButtonEdit": // 编辑
          this.buttonEdit();
          break;
        case "businessButtonDelete": // 删除
          this.buttonDelete();
          break;
        case "businessButtonViewFlow": // 查看流程
          this.buttonViewFlow();
          break;
        case "businessButtonExport": // 导出
          this.buttonExport();
          break;
        case "businessButtonImport": // 导入
          this.buttonImport();
          break;
        default:
          // 自定义
          this.buttonCustom(item);
      }
    },
    /* 按钮新增 */
    buttonAdd(item) {
      this.cellAdd = true;
      if (this.params && this.params.deptId) {
        // 有默认配置部门 ID
        this.tdeptId = this.params.deptId;
        return;
      }
      getFillDept({
        funcId: this.params && this.params.id ? null : this.menuId,
        funcCode: this.params && this.params.id ? this.params.menuCode : null,
        type: 2,
      }).then((res) => {
        if (res.info.length === 1) {
          if (item.method && item.method != null) {
            // 关联窗体
            this.relatedPageRoute = JSON.parse(item.method).route;
            // this.relatedPageRoute = JSON.parse(item.method).dblvue;
            this.relatedWinParams = {
              deptId: res.info[0].id,
              funcId: this.params && this.params.id ? null : this.menuId,
              funcCode:
                this.params && this.params.id ? this.params.menuCode : null,
            };
            if (item.type === 1) {
              // 模块
              this.buttonComShow = true;
            } else {
              // 弹窗
              this.buttonComWinShow = true;
            }
          } else {
            this.funcId = this.params && this.params.id ? null : this.menuId;
            this.funcCode =
              this.params && this.params.id ? this.params.menuCode : null;
            this.funcName = this.pageContent.text;
            this.tdeptId = res.info[0].id;
            if (this.params && this.params.businessInfo) {
              if (Object.keys(this.params.businessInfo).length > 0) {
                this.businessInfoParam = this.params.businessInfo;
              }
            }
            if (this.params && this.params.cellParams) {
              this.formateInitParam();
            } else {
              this.cellViewShow = true;
            }
          }
        } else {
          // 多个部门
          this.deptMap = res.info;
          this.deptMapShow = true;
        }
      });
    },

    async buttonEdit() {
      if (this.checkedData.length === 0) {
        this.message("请选择需要编辑的数据", 3);
        return;
      }
      if (this.checkedData.length > 1) {
        this.message("不能同时编辑多条数据", 3);
        return;
      }
      const detail = JSON.parse(JSON.stringify(this.checkedData[0]));
      this.wpId = await this.getWpId(detail);
      if (!this.wpId) {
        this.message("没有表单 ID 无法编辑", 3);
        return;
      }
      if (!detail[this.pageContent.primaryName]) {
        this.message("没有主键无法编辑", 3);
        return;
      }
      editAut({
        funcId: this.params && this.params.id ? null : this.menuId,
        funcCode: this.params && this.params.id ? this.params.menuCode : null,
        tableName: this.pageContent.tableName,
        id: detail[this.pageContent.primaryName],
        keyName: this.pageContent.primaryName,
      }).then((res) => {
        if (res.success) {
          this.workId = detail[this.pageContent.primaryName];
          this.funcName = this.pageContent.text;
          this.tdeptId = this.$store.state.user.info.deptId;
          if (this.params && this.params.businessInfo) {
            if (Object.keys(this.params.businessInfo).length > 0) {
              this.businessInfoParam = this.params.businessInfo;
            }
          }
          if (this.params && this.params.cellParams) {
            this.formateInitParam();
          } else {
            this.cellViewShow = true;
          }
        } else {
          this.message("没有编辑权限", 3);
          return;
        }
      });
    },
    buttonDelete() {
      if (this.checkedData.length === 0) {
        this.message("请选择需要删除的数据", 3);
        return;
      }
      let ids = [];
      this.checkedData.forEach((item) => {
        ids.push(item[this.pageContent.primaryName]);
      });
      this.messageBox("确认删除？").then((c) => {
        if (c.action) {
          pageRemove({
            pageId: this.pageContent.id,
            values: ids,
            menuId: this.params && this.params.id ? null : this.menuId,
            menuCode:
              this.params && this.params.id ? this.params.menuCode : null,
          }).then((res) => {
            if (res.success) {
              this.search(this.pageIndex);
              this.message(res.msg, 1);
            } else {
              this.message("数据已经存在流程中，不允许删除", 3);
            }
          });
        }
      });
    },
    /* 按钮查看流程 */
    buttonViewFlow() {
      if (this.checkedData.length > 1) {
        this.message("不能同时查看多个流程", 3);
        return;
      }
      if (this.checkedData.length === 0) {
        this.message("请选择需要查看的流程", 3);
        return;
      }
      if (this.checkedData[0].WF_STATE === 0) {
        this.message("流程未上报", 3);
        return;
      }
      this.flowViewShow = true;
      this.wfInstId = this.checkedData[0].WFINST_ID;
    },
    /* 按钮导出 */
    async buttonExport() {
      const arr = await this.getFormattingCondition();
      pageExport({
        pageId: this.pageContent.id,
        menuId: this.params && this.params.id ? null : this.menuId,
        menuCode: this.params && this.params.id ? this.params.menuCode : null,
        params: arr,
      }).then((res) => {
        if (res.success) {
          window.open(process.env.VUE_APP_BASE_API + res.info);
          this.message(res.msg, 1);
        } else {
          this.message(res.msg, 3);
          return;
        }
      });
    },
    buttonImport() {
      /* 按钮导入 */
      getFillDept({
        funcId: this.params && this.params.id ? null : this.menuId,
        funcCode: this.params && this.params.id ? this.params.menuCode : null,
        type: 2,
      }).then((res) => {
        if (res.info.length === 1) {
          this.tdeptId = res.info[0].id;
          this.form = {
            handleWay: 1,
            file: "",
          };
          this.file = null;
          this.errorMessageShow = false;
          this.importFileDialog = true;
        } else {
          this.deptMap = res.info;
          this.deptMapShow = true;
        }
      });
    },
    /* 按钮自定义 */
    buttonCustom(item) {
      /**
       * 1.点击自定义按钮，执行接口请求，用户必须选中列表中的数据，根据自定义字段名称进行传值，例如ids:[]
       * 2.如果用户不配置请求地址，执行窗体事件
       */
      if (!item.url) {
        this.message("没有配置请求地址", 3);
        return;
      }
      if (!this.checkedData.length) {
        this.message("最少选择一条数据", 3);
        return;
      }
      const paramName = JSON.parse(item.params);
      let keyArrays = Object.keys(paramName);
      const keyName = keyArrays[0];
      let paramData = this.checkedData;
      if (item.contentType == "2") {
        //JSON请求
        request({
          url: item.url,
          method: "post",
          type: 2,
          data: paramData,
        }).then((res) => {
          if (res.success) {
            //成功
            this.message(res.msg, 1);
            //执行页面数据请求
          } else {
            //失败
            this.message(res.msg, 3);
          }
        });
      }

      return;

      if (!item.url) {
        this.message("没有配置请求地址", 3);
        return;
      }
      const url = item.url;

      const params = JSON.parse(item.params);
      console.log("11112:", item);
      if (!params.multipleChoice && this.checkedData.length > 1) {
        this.message("不能操作多条数据", 3);
        return;
      }
      let data = {};
      console.log("params:" + JSON.stringify(params));
      // const obj = params.params;
      const obj = params.cellParams;

      for (let key in obj) {
        console.log("11111:", key, obj[key]);
        if (typeof obj[key] !== "object") {
          if (String(obj[key]).indexOf("@@") > "-1" && key === "menuId") {
            data.menuId = this.menuId;
          } else {
            data[key] = obj[key];
          }
        } else if (typeof obj[key].length === "number") {
          // 数组
          let arr = [];
          if (obj[key].length === 1) {
            // console.log('一个');
          }
          obj[key].forEach((item) => {
            // console.log(item);
          });
          // data[key] = []
          // const value = obj[key][0]
          //
          // this.checkedData.forEach(item => {
          //   data[key].push(item[value])
          // })
        }
      }
      // if (item.contentType === '2') { // JSON 请求
      //   request({
      //     url: url,
      //     method: 'post',
      //     type: 2,
      //     data: data,
      //   }).then((res) => {
      //     if (res.success) {
      //       this.message(res.msg, 1)
      //       this.search((this.pageIndex))
      //     } else {
      //       this.message(res.msg, 3)
      //       return
      //     }
      //   })
      // }
    },
    /* 格式化传给表单的参数 */
    formateInitParam() {
      /* initParams 传参格式 [[{"a":"aa","b":"bb","c":"cc"}],[{"a":"aa","b":"bb","c":"cc"},{"a":"aa","b":"bb","c":"cc"}]] */
      const buttonParams = JSON.parse(
        this.currentButtonDetail.params
      ).cellParams; // 按钮定义
      let mainTable = {}; // 主表
      let subTable = {}; // 子表
      buttonParams.forEach((params) => {
        if (this.params.cellParams[params]) {
          let regex = new RegExp("@", "g"); // 使用g表示整个字符串都要匹配
          let result = params.match(regex); //match方法可在字符串内检索指定的值，或找到一个或多个正则表达式的匹配
          if (result.length === 1) {
            // 主表
            mainTable[params.substring(1, this.params.cellParams.length)] =
              this.params.cellParams[params];
          } else if (result.length === 2) {
            subTable[params.substring(2, this.params.cellParams.length)] =
              this.params.cellParams[params];
          }
        }
      });
      let mainTableArr = [];
      let subTableArr = [];
      let initParamMap = [];
      if (Object.keys(mainTable).length > 0) {
        mainTableArr.push(mainTable);
        initParamMap.push(mainTableArr);
      }
      if (Object.keys(subTable).length > 0) {
        mainTableArr.push(subTableArr);
        initParamMap.push(subTableArr);
      }
      this.initParam = initParamMap;
      this.cellViewShow = true;
    },
    refreshpage() {
      this.search(this.pageIndex);
    },
    handleCellView() {
      this.cellViewShow = false;
      this.search(this.pageIndex);
    },
    getWindowData(e) {
      if (
        this.comParam.hasOwnProperty("return") &&
        this.currentDbclickComponent.hasOwnProperty("code")
      ) {
        const value = this.comParam.return[this.currentDbclickComponent.code];
        if (typeof value === "string") {
          this.searchesMap[this.currentDbclickComponent.code] = e[0][value];
        } else {
          // 键值对
          this.searchesMap[this.currentDbclickComponent.code] =
            e[0][value.label];
          this.objSearchCondition[this.currentDbclickComponent.code] =
            e[0][value.value];
        }
        this.searchComponents.forEach((item) => {
          if (item.code === this.currentDbclickComponent.code) {
            item.defaultValue =
              e[0][this.comParam.return[this.currentDbclickComponent.code]];
          }
        });
      } else {
        e.forEach((element) => {
          for (const key in element) {
            for (const outKey in this.dblParamOut) {
              if (key == outKey) {
                this.paramOut[outKey] = element[key];
              }
            }
          }
        });
        console.log(JSON.stringify(this.paramOut));
        //执行sql脚本
        sys["VUE"] = this;
        sys.func(sys, this.itemSqlBrAfter);
      }
      this.templateWindowShow = false;
    },
    windowHide() {
      this.templateWindowShow = false;
    },
    handleDeptChange(e) {
      if (e.length > 1) {
        this.$refs.table.clearSelection();
        this.$refs.table.toggleRowSelection(e.pop());
      }
      this.checkedDept = e;
    },
    getDeptId() {
      if (this.checkedDept.length === 0) {
        this.message("请选择部门", 3);
        return;
      } else {
        this.tdeptId = this.checkedDept[0].id;
        const item = this.currentButtonDetail;
        if (item.attr === "businessButtonAdd") {
          if (item.method && item.method != "null") {
            // 关联窗体
            this.relatedPageRoute = JSON.parse(item.method).route;
            this.relatedWinParams = {
              deptId: this.checkedDept[0].id,
              funcId: this.params && this.params.id ? null : this.menuId,
              funcCode:
                this.params && this.params.id ? this.params.menuCode : null,
            };
            if (item.type === 1) {
              // 模块
              this.buttonComShow = true;
            } else {
              // 弹窗
              this.buttonComWinShow = true;
            }
          } else {
            this.funcId = this.params && this.params.id ? null : this.menuId;
            this.funcCode =
              this.params && this.params.id ? this.params.menuCode : null;
            this.funcName = this.pageContent.text;
            this.wpId = "";
            this.workId = "";
            //this.wpNodeId="1504";
            if (this.params) {
              if (
                this.params.businessInfo &&
                Object.keys(this.params.businessInfo).length > 0
              ) {
                this.businessInfoParam = this.params.businessInfo;
              }
            }
            if (this.params && this.params.cellParams) {
              this.formateInitParam();
            } else {
              this.cellViewShow = true;
            }
          }
        } else if (item.attr === "businessButtonImport") {
          this.form = {
            handleWay: 1,
            file: "",
          };
          this.file = null;
          this.errorMessageShow = false;
          this.importFileDialog = true;
        }
        this.deptMapShow = false;
      }
    },
    flowViewHide() {
      this.flowViewShow = false;
    },
    // 控件双击事件
    dblclick(e) {
      if (e.method) {
        this.comParam = JSON.parse(e.params);
        if (!this.params) {
          // 传当前菜单 ID 且不是弹窗
          if (
            this.comParam.params.funcId &&
            this.comParam.params.funcId === "@@funcId"
          ) {
            this.comParam.params.funcId = this.$route.meta.funcId;
          }
        }
        if (JSON.parse(e.method) < 0) {
          // 系统组件
          switch (Number(JSON.parse(e.method))) {
            case -1: // 选人员
              this.treeParam = this.comParam.params;
              this.treeTitle = "人员选择";
              this.treeType = 2;
              this.treeShow = true;
              break;
            case -2: // 选部门
              this.treeParam = this.comParam.params;
              this.treeTitle = "部门选择";
              this.treeType = 0;
              this.treeShow = true;
              break;
            case -3: // 选模块
              this.menuTreeShow = true;
              break;
            case -4: // 选资金科目
              this.fundAccountTreeShow = true;
              break;
            default:
              // 选物资类别
              this.treeParam = this.comParam.params.param;
              this.treeParams = this.comParam.params.params;
              this.treeTitle = this.comParam.params.title;
              this.treeType = this.comParam.params.type;
              this.treeCheckbox = this.comParam.params.checkBox;
              this.dataTreeShow = true;
          }
        } else {
          // 自定义页面弹窗
          this.templateWindowParams = this.comParam.params;
          this.templateWindowShow = true;
        }
        this.currentDbclickComponent = e;
      }
    },
    getTreeData(e) {
      const componentType = JSON.parse(this.currentDbclickComponent.method);
      if (componentType === -3 || componentType === -4) {
        // 选菜单&&资金科目
        this.searchesMap[this.currentDbclickComponent.code] =
          e[this.comParam.return[this.currentDbclickComponent.code]];
        this.menuTreeShow = false;
        this.fundAccountTreeShow = false;
      } else if (componentType === -5) {
        // 物资类别
        this.searchesMap[this.currentDbclickComponent.code] =
          e[0][this.comParam.return[this.currentDbclickComponent.code]];
        this.dataTreeShow = false;
      } else {
        if (!this.comParam.return[this.currentDbclickComponent.code]) {
          this.message("没有配置返回参数", 3);
          return;
        }
        this.searchesMap[this.currentDbclickComponent.code] =
          e[0][this.comParam.return[this.currentDbclickComponent.code]];
        this.searchComponents.forEach((item) => {
          if (item.code === this.currentDbclickComponent.code) {
            item.defaultValue =
              e[0][this.comParam.return[this.currentDbclickComponent.code]];
          }
        });
        this.treeShow = false;
      }
    },
    treeHide() {
      this.menuTreeShow = false;
      this.treeShow = false;
      this.fundAccountTreeShow = false;
    },
    handleMoreConditions() {
      this.pageContentShow = false;
      this.tableShow = false;
      this.moreConditionsShow = !this.moreConditionsShow;
      setTimeout(() => {
        this.getContentHeight();
      }, 50);
    },
    visibleChange(e) {
      if (e.refer) {
        // 有级联绑定
        const arr = [
          {
            name: "@@refer",
            value: this.searchesMap[e.refer],
          },
        ];
        request({
          url: e.url,
          method: "post",
          params: {
            params: arr,
          },
        }).then((res) => {
          let map = [];
          let value = "";
          let label = "";
          const keyMap = JSON.parse(e.data);
          keyMap.forEach((item) => {
            for (let key in item) {
              if (key === "value") {
                value = item[key];
              } else if (key === "label") {
                label = item[key];
              }
            }
          });
          res.info.forEach((item) => {
            const obj = {
              value: item[value],
              label: item[label],
            };
            map.push(obj);
          });
          this.selectOption[e.code] = map;
          this.$forceUpdate();
        });
      }
    },
    handleComponentChange(e) {
      // 级联清除
      for (let key in this.searchComponents) {
        if (this.searchComponents[key].refer == e.code) {
          this.searchesMap[this.searchComponents[key].code] = null;
          return;
        }
      }
    },
    // 导入文件
    handleChange(files, fileList) {
      if (fileList.length > 0) {
        this.fileList = [fileList[fileList.length - 1]];
      }
      this.form.file = this.fileList[0].name;
      this.file = files.raw;
    },
    importFile() {
      if (!this.file) {
        this.message("请选择上传的文件", 3);
        return;
      }
      let formData = new FormData();
      formData.append("pageId", this.pageContent.id);
      formData.append("deptId", this.tdeptId);
      formData.append("handleWay", this.form.handleWay);
      formData.append("positionWay", 0);
      formData.append("file", this.file);

      // 表单数据传给后台
      if (this.params) {
        if (Object.keys(this.params.serverParams).length > 0) {
          for (let key in this.params.serverParams) {
            if (this.params.serverParams[key]) {
              formData.append(`vars[${key}]`, this.params.serverParams[key]);
            }
          }
        }
      }
      if (this.params && this.params.id) {
        // 弹窗
        formData.append("menuCode", this.params.menuCode);
      } else {
        // 模块
        formData.append("menuId", this.menuId);
      }
      pageImport(formData).then((res) => {
        if (res.success) {
          if (res.info.message) {
            this.errorMessage = res.info.message;
            this.errorMessageShow = true;
            this.errorMessageUrl = res.info.url;
          } else {
            this.importFileDialog = false;
          }
          this.search(Math.ceil(this.totalCount / this.pageSize));
          this.message(res.msg, 1);
        } else this.message(res.msg, 3);
      });
    },
    // 自定义页面弹窗
    handelTemplateWindow(e) {
      if (e === "cancel") {
        this.templateWindowShow = false;
      }
    },
    handleRelatedPage() {
      this.buttonComWinShow = false;
      this.buttonComShow = false;
      this.search(0);
    },
    addReportIn() {
      const addIn = this.buttonComponents.find(function (item) {
        return item.attr == "businessButtonAdd";
      });
      this.buttonClick(addIn, 2);
    },
  },
};
</script>

<style lang="scss" scoped>
.page-wrapper {
  &.perviewPage-wrapper {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: RGBA(242, 243, 247, 1);
    z-index: 99;
  }
}

.businessMask .businessDialog {
  .dialog-body {
    .errorMessage {
      text-align: left;
      color: red;
      white-space: pre-line;
    }

    a {
      float: left;
    }
  }

  &.relatedPage .dialog-body {
    height: calc(100% - 48px);
    padding: 0;
    overflow: hidden;

    .systemPage-wrapper {
      height: 100%;
    }
  }
}

.businessPage-wrapper .window-searches-wrapper {
  padding: 0 !important;
}

/deep/ .el-table__body-wrapper {
  height: calc(100% - 40px) !important;
}

/deep/ .el-dialog__header {
  text-align: left;
  padding: 5px;
}

/deep/ .el-dialog__body iframe {
  min-height: 500px;
  height: 500px;
}

.businessDialog .dialog-body {
  display: inherit;
}
</style>